home *** CD-ROM | disk | FTP | other *** search
/ Windows Expert / Windows Expert.iso / windownt / tusrc.zip / SRC / CUT.C < prev    next >
C/C++ Source or Header  |  1993-09-18  |  15KB  |  602 lines

  1. /* cut - remove parts of lines of files
  2.    Copyright (C) 1984 by David M. Ihnat
  3.  
  4.    This program is a total rewrite of the Bell Laboratories Unix(Tm)
  5.    command of the same name, as of System V.  It contains no proprietary
  6.    code, and therefore may be used without violation of any proprietary
  7.    agreements whatsoever.  However, you will notice that the program is
  8.    copyrighted by me.  This is to assure the program does *not* fall
  9.    into the public domain.  Thus, I may specify just what I am now:
  10.    This program may be freely copied and distributed, provided this notice
  11.    remains; it may not be sold for profit without express written consent of
  12.    the author.
  13.    Please note that I recreated the behavior of the Unix(Tm) 'cut' command
  14.    as faithfully as possible; however, I haven't run a full set of regression
  15.    tests.  Thus, the user of this program accepts full responsibility for any
  16.    effects or loss; in particular, the author is not responsible for any losses,
  17.    explicit or incidental, that may be incurred through use of this program.
  18.  
  19.    I ask that any bugs (and, if possible, fixes) be reported to me when
  20.    possible.  -David Ihnat (312) 784-4544 ignatz@homebru.chi.il.us
  21.  
  22.    POSIX changes, bug fixes, long-named options, and cleanup
  23.    by David MacKenzie <djm@gnu.ai.mit.edu>.
  24.  
  25.    Options:
  26.    --bytes=byte-list
  27.    -b byte-list            Print only the bytes in positions listed
  28.                 in BYTE-LIST.
  29.                 Tabs and backspaces are treated like any
  30.                 other character; they take up 1 byte.
  31.  
  32.    --characters=character-list
  33.    -c character-list        Print only characters in positions listed
  34.                 in CHARACTER-LIST.
  35.                 The same as -b for now, but
  36.                 internationalization will change that.
  37.                 Tabs and backspaces are treated like any
  38.                 other character; they take up 1 character.
  39.  
  40.    --fields=field-list
  41.    -f field-list        Print only the fields listed in FIELD-LIST.
  42.                 Fields are separated by a TAB by default.
  43.  
  44.    --delimiter=delim
  45.    -d delim            For -f, fields are separated by the first
  46.                 character in DELIM instead of TAB.
  47.  
  48.    -n                Do not split multibyte chars (no-op for now).
  49.  
  50.    --only-delimited
  51.    -s                For -f, do not print lines that do not contain
  52.                 the field separator character.
  53.  
  54.    The BYTE-LIST, CHARACTER-LIST, and FIELD-LIST are one or more numbers
  55.    or ranges separated by commas.  The first byte, character, and field
  56.    are numbered 1.
  57.  
  58.    A FILE of `-' means standard input. */
  59.  
  60. /* Get isblank from GNU libc.  */
  61. #define _GNU_SOURCE
  62.  
  63. #include <stdio.h>
  64. #include "../lib/getopt.h"
  65. #include <sys/types.h>
  66. #include "system.h"
  67. #include "version.h"
  68.  
  69. char *xmalloc ();
  70. char *xrealloc ();
  71. void error ();
  72.  
  73. static int set_fields ();
  74. static int cut_file ();
  75. static void cut_stream ();
  76. static void cut_bytes ();
  77. static void cut_fields ();
  78. static void enlarge_line ();
  79. static void invalid_list ();
  80. static void usage ();
  81.  
  82. /* The number of elements allocated for the input line
  83.    and the byte or field number.
  84.    Enlarged as necessary. */
  85. static int line_size;
  86.  
  87. /* Processed output buffer. */
  88. static char *outbuf;
  89.  
  90. /* Where to save next char to output. */
  91. static char *outbufptr;
  92.  
  93. /* Raw line buffer for field mode. */
  94. static char *inbuf;
  95.  
  96. /* Where to save next input char. */
  97. static char *inbufptr;
  98.  
  99. /* What can be done about a byte or field. */
  100. enum field_action
  101. {
  102.   field_omit,
  103.   field_output
  104. };
  105.  
  106. /* In byte mode, which bytes to output.
  107.    In field mode, which `delim'-separated fields to output.
  108.    Both bytes and fields are numbered starting with 1,
  109.    so the first element of `fields' is unused. */
  110. static enum field_action *fields;
  111.  
  112. enum operating_mode
  113. {
  114.   undefined_mode,
  115.  
  116.   /* Output characters that are in the given bytes. */
  117.   byte_mode,
  118.  
  119.   /* Output the given delimeter-separated fields. */
  120.   field_mode
  121. };
  122.  
  123. /* The name this program was run with. */
  124. char *program_name;
  125.  
  126. static enum operating_mode operating_mode;
  127.  
  128. /* If nonzero,
  129.    for field mode, do not output lines containing no delimeter characters. */
  130. static int delimited_lines_only;
  131.  
  132. /* The delimeter character for field mode. */
  133. static unsigned char delim;
  134.  
  135. /* Nonzero if we have ever read standard input. */
  136. static int have_read_stdin;
  137.  
  138. /* If non-zero, display usage information and exit.  */
  139. static int flag_help;
  140.  
  141. /* If non-zero, print the version on standard error.  */
  142. static int flag_version;
  143.  
  144. static struct option const longopts[] =
  145. {
  146.   {"bytes", required_argument, 0, 'b'},
  147.   {"characters", required_argument, 0, 'c'},
  148.   {"fields", required_argument, 0, 'f'},
  149.   {"delimiter", required_argument, 0, 'd'},
  150.   {"only-delimited", no_argument, 0, 's'},
  151.   {"help", no_argument, &flag_help, 1},
  152.   {"version", no_argument, &flag_version, 1},
  153.   {0, 0, 0, 0}
  154. };
  155.  
  156. void
  157. main (argc, argv)
  158.      int argc;
  159.      char **argv;
  160. {
  161.   int optc, exit_status = 0;
  162.  
  163.   program_name = argv[0];
  164.  
  165.   line_size = 512;
  166.   operating_mode = undefined_mode;
  167.   delimited_lines_only = 0;
  168.   delim = '\0';
  169.   have_read_stdin = 0;
  170.  
  171.   fields = (enum field_action *)
  172.     xmalloc (line_size * sizeof (enum field_action));
  173.   outbuf = (char *) xmalloc (line_size);
  174.   inbuf = (char *) xmalloc (line_size);
  175.  
  176.   for (optc = 0; optc < line_size; optc++)
  177.     fields[optc] = field_omit;
  178.  
  179.   while ((optc = getopt_long (argc, argv, "b:c:d:f:ns", longopts, (int *) 0))
  180.      != EOF)
  181.     {
  182.       switch (optc)
  183.     {
  184.     case 0:
  185.       break;
  186.  
  187.     case 'b':
  188.     case 'c':
  189.       /* Build the byte list. */
  190.       if (operating_mode != undefined_mode)
  191.         usage ();
  192.       operating_mode = byte_mode;
  193.       if (set_fields (optarg) == 0)
  194.         error (2, 0, "no fields given");
  195.       break;
  196.  
  197.     case 'f':
  198.       /* Build the field list. */
  199.       if (operating_mode != undefined_mode)
  200.         usage ();
  201.       operating_mode = field_mode;
  202.       if (set_fields (optarg) == 0)
  203.         error (2, 0, "no fields given");
  204.       break;
  205.  
  206.     case 'd':
  207.       /* New delimiter. */
  208.       if (optarg[0] == '\0')
  209.         error (2, 0, "no delimiter given");
  210.       if (optarg[1] != '\0')
  211.         error (2, 0, "delimiter must be a single character");
  212.       delim = optarg[0];
  213.       break;
  214.  
  215.     case 'n':
  216.       break;
  217.  
  218.     case 's':
  219.       delimited_lines_only++;
  220.       break;
  221.  
  222.     default:
  223.       usage ();
  224.     }
  225.     }
  226.  
  227.   if (flag_version)
  228.     {
  229.       fprintf (stderr, "%s\n", version_string);
  230.       exit (0);
  231.     }
  232.  
  233.   if (flag_help)
  234.     usage ();
  235.  
  236.   if (operating_mode == undefined_mode)
  237.     usage ();
  238.  
  239.   if ((delimited_lines_only || delim != '\0') && operating_mode != field_mode)
  240.     usage ();
  241.  
  242.   if (delim == '\0')
  243.     delim = '\t';
  244.  
  245.   if (optind == argc)
  246.     exit_status |= cut_file ("-");
  247.   else
  248.     for (; optind < argc; optind++)
  249.       exit_status |= cut_file (argv[optind]);
  250.  
  251.   if (have_read_stdin && fclose (stdin) == EOF)
  252.     {
  253.       error (0, errno, "-");
  254.       exit_status = 1;
  255.     }
  256.   if (ferror (stdout) || fclose (stdout) == EOF)
  257.     error (1, errno, "write error");
  258.  
  259.   exit (exit_status);
  260. }
  261.  
  262. /* Select for printing the positions in `fields' that are listed in
  263.    byte or field specification FIELDSTR.  FIELDSTR should be
  264.    composed of one or more numbers or ranges of numbers, separated by
  265.    blanks or commas.  Incomplete ranges may be given: `-m' means
  266.    `1-m'; `n-' means `n' through end of line or last field.
  267.  
  268.    Return the number of fields selected. */
  269.  
  270. static int
  271. set_fields (fieldstr)
  272.      char *fieldstr;
  273. {
  274.   int initial = 1;        /* Value of first number in a range. */
  275.   int dash_found = 0;        /* Nonzero if a '-' is found in this field. */
  276.   int value = 0;        /* If nonzero, a number being accumulated. */
  277.   int fields_selected = 0;    /* Number of fields selected so far. */
  278.   /* If nonzero, index of first field in a range that goes to end of line. */
  279.   int eol_range_start = 0;
  280.  
  281.   for (;;)
  282.     {
  283.       if (*fieldstr == '-')
  284.     {
  285.       /* Starting a range. */
  286.       if (dash_found)
  287.         invalid_list ();
  288.       dash_found++;
  289.       fieldstr++;
  290.  
  291.       if (value)
  292.         {
  293.           if (value >= line_size)
  294.         enlarge_line (value);
  295.           initial = value;
  296.           value = 0;
  297.         }
  298.       else
  299.         initial = 1;
  300.     }
  301.       else if (*fieldstr == ',' || ISBLANK (*fieldstr) || *fieldstr == '\0')
  302.     {
  303.       /* Ending the string, or this field/byte sublist. */
  304.       if (dash_found)
  305.         {
  306.           dash_found = 0;
  307.  
  308.           /* A range.  Possibilites: -n, m-n, n-.
  309.          In any case, `initial' contains the start of the range. */
  310.           if (value == 0)
  311.         {
  312.           /* `n-'.  From `initial' to end of line. */
  313.           eol_range_start = initial;
  314.           fields_selected++;
  315.         }
  316.           else
  317.         {
  318.           /* `m-n' or `-n' (1-n). */
  319.           if (value < initial)
  320.             invalid_list ();
  321.  
  322.           if (value >= line_size)
  323.             enlarge_line (value);
  324.  
  325.           /* Is there already a range going to end of line? */
  326.           if (eol_range_start != 0)
  327.             {
  328.               /* Yes.  Is the new sequence already contained
  329.              in the old one?  If so, no processing is
  330.              necessary. */
  331.               if (initial < eol_range_start)
  332.             {
  333.               /* No, the new sequence starts before the
  334.                  old.  Does the old range going to end of line
  335.                  extend into the new range?  */
  336.               if (eol_range_start < value)
  337.                 /* Yes.  Simply move the end of line marker. */
  338.                 eol_range_start = initial;
  339.               else
  340.                 {
  341.                   /* No.  A simple range, before and disjoint from
  342.                  the range going to end of line.  Fill it. */
  343.                   for (; initial <= value; initial++)
  344.                 fields[initial] = field_output;
  345.                 }
  346.  
  347.               /* In any case, some fields were selected. */
  348.               fields_selected++;
  349.             }
  350.             }
  351.           else
  352.             {
  353.               /* There is no range going to end of line. */
  354.               for (; initial <= value; initial++)
  355.             fields[initial] = field_output;
  356.               fields_selected++;
  357.             }
  358.           value = 0;
  359.         }
  360.         }
  361.       else if (value != 0)
  362.         {
  363.           /* A simple field number, not a range. */
  364.           if (value >= line_size)
  365.         enlarge_line (value);
  366.  
  367.           fields[value] = field_output;
  368.           value = 0;
  369.           fields_selected++;
  370.         }
  371.  
  372.       if (*fieldstr == '\0')
  373.         {
  374.           /* If there was a range going to end of line, fill the
  375.          array from the end of line point.  */
  376.           if (eol_range_start)
  377.         for (initial = eol_range_start; initial < line_size; initial++)
  378.           fields[initial] = field_output;
  379.  
  380.           return fields_selected;
  381.         }
  382.  
  383.       fieldstr++;
  384.     }
  385.       else if (ISDIGIT (*fieldstr))
  386.     {
  387.       value = 10 * value + *fieldstr - '0';
  388.       fieldstr++;
  389.     }
  390.       else
  391.     invalid_list ();
  392.     }
  393. }
  394.  
  395. /* Process file FILE to standard output.
  396.    Return 0 if successful, 1 if not. */
  397.  
  398. static int
  399. cut_file (file)
  400.      char *file;
  401. {
  402.   FILE *stream;
  403.  
  404.   if (!strcmp (file, "-"))
  405.     {
  406.       have_read_stdin = 1;
  407.       stream = stdin;
  408.     }
  409.   else
  410.     {
  411.       stream = fopen (file, "r");
  412.       if (stream == NULL)
  413.     {
  414.       error (0, errno, "%s", file);
  415.       return 1;
  416.     }
  417.     }
  418.  
  419.   cut_stream (stream);
  420.  
  421.   if (ferror (stream))
  422.     {
  423.       error (0, errno, "%s", file);
  424.       return 1;
  425.     }
  426.   if (!strcmp (file, "-"))
  427.     clearerr (stream);        /* Also clear EOF. */
  428.   else if (fclose (stream) == EOF)
  429.     {
  430.       error (0, errno, "%s", file);
  431.       return 1;
  432.     }
  433.   return 0;
  434. }
  435.  
  436. static void
  437. cut_stream (stream)
  438.      FILE *stream;
  439. {
  440.   if (operating_mode == byte_mode)
  441.     cut_bytes (stream);
  442.   else
  443.     cut_fields (stream);
  444. }
  445.  
  446. /* Print the file open for reading on stream STREAM
  447.    with the bytes marked `field_omit' in `fields' removed from each line. */
  448.  
  449. static void
  450. cut_bytes (stream)
  451.      FILE *stream;
  452. {
  453.   register int c;        /* Each character from the file. */
  454.   int doneflag = 0;        /* Nonzero if EOF reached. */
  455.   int char_count;        /* Number of chars in the line so far. */
  456.  
  457.   while (doneflag == 0)
  458.     {
  459.       /* Start processing a line. */
  460.       outbufptr = outbuf;
  461.       char_count = 0;
  462.  
  463.       do
  464.     {
  465.       c = getc (stream);
  466.       if (c == EOF)
  467.         {
  468.           doneflag++;
  469.           break;
  470.         }
  471.  
  472.       /* If this character is to be sent, stow it in the outbuffer. */
  473.  
  474.       if (++char_count == line_size - 1)
  475.         enlarge_line (char_count);
  476.  
  477.       if (fields[char_count] == field_output || c == '\n')
  478.         *outbufptr++ = c;
  479.     }
  480.       while (c != '\n');
  481.  
  482.       if (char_count)
  483.     fwrite (outbuf, sizeof (char), outbufptr - outbuf, stdout);
  484.     }
  485. }
  486.  
  487. /* Print the file open for reading on stream STREAM
  488.    with the fields marked `field_omit' in `fields' removed from each line.
  489.    All characters are initially stowed in the raw input buffer, until
  490.    at least one field has been found. */
  491.  
  492. static void
  493. cut_fields (stream)
  494.      FILE *stream;
  495. {
  496.   register int c;        /* Each character from the file. */
  497.   int doneflag = 0;        /* Nonzero if EOF reached. */
  498.   int char_count;        /* Number of chars in line before any delim. */
  499.   int fieldfound;        /* Nonzero if any fields to print found. */
  500.   int curr_field;        /* Current index in `fields'. */
  501.  
  502.   while (doneflag == 0)
  503.     {
  504.       char_count = 0;
  505.       fieldfound = 0;
  506.       curr_field = 1;
  507.       outbufptr = outbuf;
  508.       inbufptr = inbuf;
  509.  
  510.       do
  511.     {
  512.       c = getc (stream);
  513.       if (c == EOF)
  514.         {
  515.           doneflag++;
  516.           break;
  517.         }
  518.  
  519.       if (fields[curr_field] == field_output && c != '\n')
  520.         {
  521.           /* Working on a field.  It, and its terminating
  522.          delimiter, go only into the processed buffer. */
  523.           fieldfound = 1;
  524.           if (outbufptr - outbuf == line_size - 2)
  525.         enlarge_line (outbufptr - outbuf);
  526.           *outbufptr++ = c;
  527.         }
  528.       else if (fieldfound == 0)
  529.         {
  530.           if (++char_count == line_size - 1)
  531.         enlarge_line (char_count);
  532.           *inbufptr++ = c;
  533.         }
  534.  
  535.       if (c == delim && ++curr_field == line_size - 1)
  536.         enlarge_line (curr_field);
  537.     }
  538.       while (c != '\n');
  539.  
  540.       if (fieldfound)
  541.     {
  542.       /* Something was found. Print it. */
  543.       if ((unsigned char) outbufptr[-1] == delim)
  544.         --outbufptr;    /* Suppress trailing delimiter. */
  545.  
  546.       fwrite (outbuf, sizeof (char), outbufptr - outbuf, stdout);
  547.       if (c == '\n')
  548.         putc (c, stdout);
  549.     }
  550.       else if (!delimited_lines_only && char_count)
  551.     /* A line with some characters, no delimiters, and no
  552.        suppression.  Print it. */
  553.     fwrite (inbuf, sizeof (char), inbufptr - inbuf, stdout);
  554.     }
  555. }
  556.  
  557. /* Extend the buffers to accomodate at least NEW_SIZE characters. */
  558.  
  559. static void
  560. enlarge_line (new_size)
  561.      int new_size;
  562. {
  563.   char *newp;
  564.   int i;
  565.  
  566.   new_size += 256;        /* Leave some room to grow. */
  567.  
  568.   fields = (enum field_action *)
  569.     xrealloc (fields, new_size * sizeof (enum field_action));
  570.  
  571.   newp = (char *) xrealloc (outbuf, new_size);
  572.   outbufptr += newp - outbuf;
  573.   outbuf = newp;
  574.  
  575.   newp = (char *) xrealloc (inbuf, new_size);
  576.   inbufptr += newp - inbuf;
  577.   inbuf = newp;
  578.  
  579.   for (i = line_size; i < new_size; i++)
  580.     fields[i] = field_omit;
  581.   line_size = new_size;
  582. }
  583.  
  584. static void
  585. invalid_list ()
  586. {
  587.   error (2, 0, "invalid byte or field list");
  588. }
  589.  
  590. static void
  591. usage ()
  592. {
  593.   fprintf (stderr, "\
  594. Usage: %s {-b byte-list,--bytes=byte-list} [-n] [file...] <options> \n\
  595.        %s {-c character-list,--characters=character-list} <options> [file...]\n\
  596.        %s {-f field-list,--fields=field-list} [-d delim] [-s] \n\
  597.        [--delimiter=delim] [--only-delimited] <options> [file...]\n\
  598.   Options: [--help] [--version]\n",
  599.        program_name, program_name, program_name);
  600.   exit (2);
  601. }
  602.